package com.reny.git.imgload.glide

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.annotation.NonNull
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.transition.Transition
import com.reny.git.imgload.R
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

class ImgUtils private constructor(){
    companion object{
        val instance: ImgUtils by lazy { ImgUtils() }
    }

    var header = hashMapOf<String, String>(
        /*Pair<String, String>("", ""),
        Pair<String, String>("", "")*/
    )
    var placeHolder: Int = R.mipmap.img_holder
    var errorHolder: Int = R.mipmap.img_holder
    var fallbackHolder: Int = R.mipmap.img_holder

    var loader:ILoader = GlideLoader()

    fun initLoader(loader:ILoader,
                   @DrawableRes placeHolder: Int? = null,
                   @DrawableRes errorHolder: Int? = null,
                   @DrawableRes fallbackHolder: Int? = null){
        this.loader = loader
        placeHolder?.let {
            this.placeHolder = it
        }
        errorHolder?.let {
            this.errorHolder = it
        }
        fallbackHolder?.let {
            this.fallbackHolder = it
        }
    }


    //缓存到磁盘中 非内存中
    fun cache(
        context: Context,
        model: Any?,
        width: Int? = null,
        height: Int? = null
    ){
        loader.cache(context, model, width, height)
    }

    //先调用cache后才能调用  加载缓存的图片
    fun displayCache(view: View, model: Any?){
        loader.displayCache(view, model)
    }

    fun loadBitmap(
        context: Context,
        model: Any?,
        callBack: (Bitmap?)->Unit
    ){
        loader.loadBitmap(context, model, callBack)
    }

    fun loadDrawable(
        context: Context,
        model: Any?,
        callBack: (Drawable?)->Unit
    ){
        loader.loadDrawable(context, model, callBack)
    }

    //下载完成 需要自己存储返回的File
    fun downLoadImg(
        context: Context,
        model: Any?,
        callBack: (File?)->Unit
    ){
        loader.downLoadImg(context, model, callBack)
    }

    fun pauseRequests(context: Context){
        loader.pauseRequests(context)
    }

    fun resumeRequests(context: Context){
        loader.resumeRequests(context)
    }


    fun gcBitmap(bitmap: Bitmap?) {
        if (null != bitmap && !bitmap.isRecycled) {
            bitmap.recycle()
            System.gc()
        }
    }

    fun onTrimMemory(context: Context, level: Int) {
        Glide.get(context).trimMemory(level)
    }

    fun onLowMemory(context: Context) {
        Glide.get(context).onLowMemory()
    }


    fun clearAll(context: Context){
        clearDiskCache(context)
        clearMemory(context)
    }

    private fun clearMemory(context: Context) {
        Glide.get(context).clearMemory()
    }

    private fun clearDiskCache(context: Context) {
        GlobalScope.launch {
            Glide.get(context).clearDiskCache()
        }
    }
}

fun Any.getImgLoader():ILoader = ImgUtils.instance.loader

/*fun Any.displayHead(@NonNull view: View, model:Any?){
    display(view, model, placeHolder = R.mipmap.img_head_defalt, errorHolder = R.mipmap.img_head_defalt, fallbackHolder = R.mipmap.img_head_defalt)
}*/

/*fun Any.displayBook(@NonNull view: View, model:Any?, isDark:Boolean = false){
    val defaultImg = if(isDark) R.mipmap.ic_book_empty_dark else R.mipmap.ic_book_empty
    display(view, model ?: defaultImg, placeHolder = defaultImg, errorHolder = defaultImg, fallbackHolder = defaultImg)
}*/

fun Any.display(@NonNull view: View, model:Any?,
                header : HashMap<String, String> = ImgUtils.instance.header,
                radius : Int = 0, isBlur: Boolean = false,
                @DrawableRes placeHolder: Int = ImgUtils.instance.placeHolder,
                @DrawableRes errorHolder: Int = ImgUtils.instance.errorHolder,
                @DrawableRes fallbackHolder: Int = ImgUtils.instance.fallbackHolder
){
    ImgUtils.instance.loader.display(view, model, this, header, radius, isBlur, placeHolder, errorHolder, fallbackHolder)
}

fun Any.displayTarget(@NonNull view: ImageView, model:Any?, target: ImageViewTarget<Bitmap>){
    ImgUtils.instance.loader.displayTarget(view, model, target, this)
}


fun Any.configUrlHeader(url: Any?, header : HashMap<String, String> = ImgUtils.instance.header): Any? {
    if (header.isNotEmpty()) {
        if (url != null && url is String) {
            if (url.startsWith("http")) { //网络url(以http开头 包括https)
                val builder = LazyHeaders.Builder()
                for (key in header.keys) {
                    header[key]?.let {
                        builder.addHeader(
                            key,
                            it
                        )
                    }
                }
                return GlideUrl(url, builder.build())
            }
        }
    }
    return url
}

fun RequestBuilder<Drawable>.intoBg(view: View) {
    into(object : CustomViewTarget<View, Drawable>(view) {
        override fun onResourceCleared(placeholder: Drawable?) {
            view.background = placeholder
        }

        override fun onLoadFailed(errorDrawable: Drawable?) {
            view.background = errorDrawable
        }

        override fun onResourceReady(
            resource: Drawable,
            transition: Transition<in Drawable>?
        ) {
            view.background = resource
        }
    })
}


